package com.eco.mam.work.request.resource;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.eco.mam.work.DataException;

/*Responsible for loading resources(properties file)*/
public class Resources {
	static final Logger logger = Logger.getLogger(Resources.class);

	private    Map<String, Properties> resourceMap = null;
	private  Properties properties = null;

	/*
	 * this method is used to load the requested file and returns properties.
	 * The requested file is used to map all input,output file/directory and
	 * database information
	 */
	public final  Properties load(final String strFileName) throws DataException {
		if (logger.isInfoEnabled()) {
			logger.debug("Entering Resources load() method :");
		}
		if (resourceMap != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("if (resourceMap != null)");
			}
			if (resourceMap.containsKey("workrequestconfig")) {

				properties = resourceMap.get("workrequestconfig");
			}
		} else {
			properties = new Properties();

			StringBuffer resourceName = new StringBuffer(
					System.getProperty("user.dir")).append("\\").append(
					"src\\main\\config\\");

			resourceName.append(strFileName);
			resourceName.append(".properties");
			if (logger.isDebugEnabled()) {
				logger.debug("Property file name  :" + resourceName);
			}
			FileInputStream inStream=null;
			try {

				 inStream = new FileInputStream(resourceName.toString());
				properties.load(inStream);

				resourceMap = new HashMap<String, Properties>();
				resourceMap.put("config", properties);
			} catch (IOException e) {

				throw new DataException(
						"Exception  happened,can not load  or access file from "
								+ "  :" + resourceName, e);

			}
			finally{
				if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					if (logger.isDebugEnabled()) {
						logger.debug(e);
					}
				}	
				}
			}

		}

		return properties;
	}
}
